import { gateway } from './env'
import axios from 'axios'
import { catchError } from '../common/utils/catch_error'


//网络请求配置.
export const qunInstance = axios.create({
    baseURL: '/api',          //gateway
    timeout: 20000
})

// 请求拦截器
qunInstance.interceptors.request.use(
    config => {
        const token = sessionStorage.getItem('token')
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token
        }
        config.headers['Content-Type'] = 'application/json'
        // console.log(config)
        return config
    },
    error => {
    }
)
// 响应拦截器
qunInstance.interceptors.response.use(
    res => {
        return Promise.resolve(res)
    },
    error => {
        const { response } = error
        catchError(response)
    }
)


export async function initUrl (url = '', data = {}, type = 'POST') {
    type = type.toUpperCase()
    if (type === 'GET') {
        try {
            let res = await qunInstance.get(url, { params: data })
            return new Promise((resolve) => {

                if (res.status == 200) {
                    if (res.data.code == 1500) {
                        res.status = res.data.code
                        catchError(res)
                    } else {
                        resolve(res)
                    }
                } else {
                    res.status = res.data.code
                    catchError(res)
                }
            })
        } catch (err) {

        }
    } else {
        try {
            let res = await qunInstance.post(url, data)
            return new Promise((resolve) => {
                if (res.status == 200) {
                    if (res.code == 1500) {
                        res.status = res.code
                        catchError(res)
                    } else {
                        resolve(res)
                    }
                } else {
                    res.status = res.data.code
                    catchError(res)
                }
            })
        } catch (err) {
            catchError(err)
        }
    }
}
